package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net"
	"os"
)

var (
	fileName = "./info.txt"
)

func main() {

	server, err := net.Listen("tcp", "localhost:9000")
	if err != nil {
		fmt.Println("服务创建失败：", err)
	}

	fmt.Println("等待客户端连接...")

	for {
		conn, err := server.Accept()
		if err != nil {
			fmt.Println("接收失败：", err)
		}

		handleConnection(conn)

	}

}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	fmt.Println("来自客户端的连接成功：", conn.RemoteAddr())
	buffer := make([]byte, 1024)
	recLen, err := conn.Read(buffer)
	if err != nil {
		fmt.Println("读取失败：", err)
	}

	strBuffer := string(buffer[:recLen])
	fmt.Println("Message:", strBuffer, " len:", recLen)

	// sendLen, err := conn.Write([]byte("Your message is :" + strBuffer))
	// if err != nil {
	// 	fmt.Println("send message error", err)
	// }

	// 服务在收到信息后写入文件中（追加）
	writeToCurrentFile(strBuffer)

	fmt.Println("send message success")

}

func writeToCurrentFile(strBuffer string) {
	var acceptMap map[string]interface{}

	json.Unmarshal([]byte(strBuffer), &acceptMap)
	age := acceptMap["age"]
	name := acceptMap["name"]
	sex := acceptMap["sex"]

	_, err := os.Stat(fileName)
	var exist = true
	if os.IsNotExist(err) {
		exist = false
	}

	var f *os.File
	var err1 error
	if exist { // 追加
		f, err1 = os.OpenFile(fileName, os.O_APPEND, 0666)
	} else { // 创建
		f, err1 = os.Create(fileName)
	}
	defer f.Close()

	if err1 != nil {
		fmt.Println("打开或创建文件失败：", err)
	}

	nameStr := fmt.Sprintf("姓名：%v\n\r", name)
	sexStr := fmt.Sprintf("性别：%v\n\r", sex)
	ageStr := fmt.Sprintf("年龄：%v\n\r", age)

	_, err1 = io.WriteString(f, nameStr+sexStr+ageStr+"\n\r")
	if err1 != nil {
		fmt.Println("写入失败：", err1)
	}

}
